package com.yhny.lykj.yuhannongye.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.longsichao.lscframe.ctrl.DataManager;
import com.longsichao.lscframe.model.LSCModel;
import com.longsichao.lscframe.net.HttpConnection;
import com.longsichao.lscframe.view.LSCToast;
import com.yhny.lykj.yuhannongye.Adapter.OrderInfoAdapter;
import com.yhny.lykj.yuhannongye.Adapter.OrderInfoFromCarListAdapter;
import com.yhny.lykj.yuhannongye.Adapter.ShopcartOrderAdapter;
import com.yhny.lykj.yuhannongye.R;
import com.yhny.lykj.yuhannongye.app.BaseActivity;
import com.yhny.lykj.yuhannongye.app.LSCGridLayoutManager;
import com.yhny.lykj.yuhannongye.app.UserConfig;
import com.yhny.lykj.yuhannongye.model.AboutModel;
import com.yhny.lykj.yuhannongye.model.AddressInfoModel;
import com.yhny.lykj.yuhannongye.model.AddressInfoModel1;
import com.yhny.lykj.yuhannongye.model.AddressListModel;
import com.yhny.lykj.yuhannongye.model.BaseModel;
import com.yhny.lykj.yuhannongye.model.CarListModel;
import com.yhny.lykj.yuhannongye.model.CreatOrderModel;
import com.yhny.lykj.yuhannongye.model.OrderInfoModel;
import com.yhny.lykj.yuhannongye.model.PayTotalModel;
import com.yhny.lykj.yuhannongye.net.NetHelper;
import com.yhny.lykj.yuhannongye.tools.LCLog;
import com.yhny.lykj.yuhannongye.tools.Tools;
import com.yhny.lykj.yuhannongye.view.NestedExpandableListView;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 订单详情
 */
public class OrderInfoActivity extends BaseActivity {

    private LinearLayout addAddressLl;
    private LinearLayout order_ll;
    private RelativeLayout addressRl;
    private TextView phoneTv;
    private TextView userNameTv;
    private TextView addressInfoTv;
    private TextView allTv;
    private TextView wuliuTv;
    private TextView wuliunumTv;
    private TextView stateTv;
    private Button submitBt1;
    private Button submitBt2;
    private Button submitBt3;
    private Button submitBt4;
    private Button submitBt5;
    private CarListModel carListModel;
    private ArrayList<CarListModel.ListEntity> list;
    private int fromType;
    private int freight = 12;//运费
    private int price = 0;//实际付款积分总价
    private int total = 0;//积分总价
    private String moneyPrice = "";//现金总价
    private String cartID ;//购物车id ，号分隔
    private  List<PayTotalModel> payTotalModelList;
    private String orderId;
    private CreatOrderModel creatOrderModel;
    private RecyclerView recyclerView;
    private OrderInfoModel orderInfoModel;//获取订单详情
    private ArrayList<OrderInfoModel.InfoEntity> orderList;
    private ArrayList<OrderInfoModel.DataEntity> orderShopList;
    private OrderInfoAdapter orderInfoAdapter;
    private NestedExpandableListView exListView;
    private ShopcartOrderAdapter shopcartExpandableListViewAdapter;
    private String cityid = "";//城市id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_info);
        fromType = getIntent().getIntExtra(FROM_TYPE_ID,0);
        TextView topName = (TextView)findViewById(R.id.name_top_bar);
        topName.setText("订单详情");
        findViewById(R.id.left_group).setOnClickListener(this);
        findViewById(R.id.left_text).setOnClickListener(this);
        exListView = (NestedExpandableListView)findViewById(R.id.order_goods);

        addAddressLl = (LinearLayout)findViewById(R.id.add_address);//添加收货地址
        order_ll = (LinearLayout)findViewById(R.id.order_ll);//订单状态

        addressRl = (RelativeLayout)findViewById(R.id.address_rl);//收货地址

        userNameTv = (TextView)findViewById(R.id.address_name);//收货人姓名
        phoneTv = (TextView)findViewById(R.id.address_phone);//收货人电话
        wuliuTv = (TextView)findViewById(R.id.order_wuliu);//物流
        wuliunumTv = (TextView)findViewById(R.id.order_wuliunum);//物流
        addressInfoTv = (TextView)findViewById(R.id.address_info);//收货地址详情
        stateTv = (TextView)findViewById(R.id.order_state);//订单状态
        allTv = (TextView)findViewById(R.id.order_all);//付款金额
        recyclerView = (RecyclerView)findViewById(R.id.list);
        submitBt1 = (Button)findViewById(R.id.order_submit1);
        submitBt1.setOnClickListener(this);
        submitBt2 = (Button)findViewById(R.id.order_submit2);
        submitBt2.setOnClickListener(this);
        submitBt3 = (Button)findViewById(R.id.order_submit3);
        submitBt3.setOnClickListener(this);
        submitBt4 = (Button)findViewById(R.id.order_submit4);
        submitBt4.setOnClickListener(this);
        submitBt5 = (Button)findViewById(R.id.order_submit5);
        submitBt5.setOnClickListener(this);
        showProgressDialog(R.string.text_loading);
        orderInfoModel = new OrderInfoModel();
        if (fromType==FROM_TYPE_VIEW_CAR_LIST){
            //购物车
            recyclerView.setVisibility(View.GONE);
            order_ll.setVisibility(View.GONE);
            addressRl.setOnClickListener(this);
            addAddressLl.setOnClickListener(this);

            String gson = getIntent().getStringExtra(CAR_LIST_DATA);
            Gson toGson = new GsonBuilder().serializeNulls().create();
            LCLog.e("gson = "+gson);
            carListModel = toGson.fromJson(gson, CarListModel.class);
            shopcartExpandableListViewAdapter = new ShopcartOrderAdapter(carListModel.list,this);
            exListView.setAdapter(shopcartExpandableListViewAdapter);
            for (int i = 0; i < shopcartExpandableListViewAdapter.getGroupCount(); i++)
            {
                exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
            }
            list = new ArrayList<>();
            for (int i=0;i<carListModel.list.size();i++){
                list.addAll(carListModel.list);
            }
            String price = getIntent().getStringExtra(CAR_LIST_PRICE);
            cartID = getIntent().getStringExtra(CAR_LIST_ID);
            allTv.setText(""+price+"元");
            submitBt5.setVisibility(View.GONE);//取消订单
            submitBt4.setVisibility(View.GONE);//去支付
            submitBt3.setVisibility(View.GONE);//评价
            submitBt2.setVisibility(View.VISIBLE);//查看物流
            submitBt1.setVisibility(View.VISIBLE);//确认收货
            DataManager.getData(MODEL_PROCESS_0, NetHelper.User.getAddress(), this);//获取默认地址
        } else if (fromType == FROM_TYPE_VIEW_ORDER_LIST) {
            //订单
            exListView.setVisibility(View.GONE);
            order_ll.setVisibility(View.VISIBLE);
            final LSCGridLayoutManager layoutManager1 = new LSCGridLayoutManager(this,1);
            layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(layoutManager1);
            recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).sizeResId(R.dimen.item_divider_size).colorResId(R.color.colorDivider_line).build());
            orderId = getIntent().getStringExtra(ORDER_ID);
            orderShopList = new ArrayList<>();
            orderInfoAdapter = new OrderInfoAdapter(orderShopList,this);
            recyclerView.setAdapter(orderInfoAdapter);
            DataManager.getData(MODEL_PROCESS_1, NetHelper.Order.getOrderInfo(orderId), this);//获取订单详情
        }


    }

    @Override
    public boolean onModel(int caseId, LSCModel model) {
        if (super.onModel(caseId, model)) {
            dismissProgressDialog();
            return false;
        }
        switch (caseId){
            case MODEL_PROCESS_3:{
                //确认收货
                BaseModel baseModel = (BaseModel)model;
                if (model == null || model.equals("")){
                    LSCToast.show(this,"操作失败！");
                }else{
                    LCLog.e("msg = "+baseModel.msg+",baseModel.status = "+baseModel.status);
                    if (baseModel.status==NET_SUSSEC) {
                        LSCToast.show(this, "操作成功");
                        submitBt5.setVisibility(View.GONE);
                    }else{
                        LSCToast.show(this, "操作失败");
                    }
                }
                break;
            }
            case MODEL_PROCESS_2:{
                //取消订单
                BaseModel baseModel = (BaseModel)model;
                if (isDataEmpty(baseModel)){
                    LSCToast.show(this,"取消订单失败！");
                }else{
                    LSCToast.show(this,baseModel.msg);
                    finish();
                }
                break;
            }
            case MODEL_PROCESS_1:{
                //订单详情
                orderInfoModel =(OrderInfoModel)model;
                if (isDataEmpty(orderInfoModel)){
                    LSCToast.show(this,"获取订单数据失败");
                }else{

                    orderShopList.clear();
                    orderShopList.addAll(orderInfoModel.list);
                    orderInfoAdapter.notifyDataSetChanged();
                    addAddressLl.setVisibility(View.GONE);
                    addressRl.setVisibility(View.VISIBLE);
                    userNameTv.setText(orderInfoModel.mes.person);
                    phoneTv.setText(orderInfoModel.mes.tel);
                    addressInfoTv.setText(orderInfoModel.mes.address);
                    allTv.setText(""+orderInfoModel.mes.pay);//付款金额
                  if (orderInfoModel.mes.orderstate==0){
                        // 待发货
                        stateTv.setText("待发货");
                        submitBt5.setVisibility(View.GONE);//确认收货
                        submitBt4.setVisibility(View.GONE);//查看物流
                        submitBt3.setVisibility(View.GONE);//评价
                        submitBt2.setVisibility(View.GONE);//去支付
                        submitBt1.setVisibility(View.GONE);//取消订单
                    }else if (orderInfoModel.mes.orderstate==1){
                        // 待收货
                        stateTv.setText("已发货");
                        submitBt5.setVisibility(View.VISIBLE);//确认收货
                        submitBt4.setVisibility(View.GONE);//查看物流
                        submitBt3.setVisibility(View.GONE);//评价
                        submitBt2.setVisibility(View.GONE);//去支付
                        submitBt1.setVisibility(View.GONE);//取消订单
                    }else if (orderInfoModel.mes.orderstate== 2){
                        // 完成
                        stateTv.setText("完成");
                        submitBt5.setVisibility(View.GONE);//确认收货
                        submitBt4.setVisibility(View.GONE);//查看物流
                        submitBt3.setVisibility(View.GONE);//评价
                        submitBt2.setVisibility(View.GONE);//去支付
                        submitBt1.setVisibility(View.GONE);//取消订单
                    }
                }
                break;
            }
            case MODEL_PROCESS_0:{
                AddressInfoModel1 addressListModel =(AddressInfoModel1)model;
                if (isDataEmpty(addressListModel)){
                    //沒有默認地址
                    addAddressLl.setVisibility(View.VISIBLE);
                    addressRl.setVisibility(View.GONE);

                }else{
                    //
                    if (addressListModel!=null){
                        //有默認地址
                        addAddressLl.setVisibility(View.GONE);
                        addressRl.setVisibility(View.VISIBLE);
                        userNameTv.setText(addressListModel.data.name);
                        phoneTv.setText(addressListModel.data.mobile);
                        addressInfoTv.setText(addressListModel.data.address);

                    }else{
                        //沒有默認地址
                        addAddressLl.setVisibility(View.VISIBLE);
                        addressRl.setVisibility(View.GONE);
                    }
                }
                break;
            }
        }
        dismissProgressDialog();
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data!=null) {
            switch (resultCode) {
                case FROM_TYPE_VIEW_CREAT_ORDER: {
                    String name = data.getStringExtra("name");
                    String mobile = data.getStringExtra("mobile");
                    String address = data.getStringExtra("address");
                    String id = data.getStringExtra("cityid");
                    addAddressLl.setVisibility(View.GONE);
                    addressRl.setVisibility(View.VISIBLE);
                        userNameTv.setText(""+name);
                        phoneTv.setText(""+mobile);
                        addressInfoTv.setText(""+address);
                    cityid =id;
                    break;
                }
                case FROM_TYPE_VIEW_CAR_LIST: {
                    int fromView = getIntent().getIntExtra(FROM_TYPE_ID,0);
                    Intent intent = new Intent(this, MainActivity.class);
                    intent.putExtra(FROM_TYPE_ID,fromView);
                    setResult(fromView, intent);
                    finish();
                    break;
                }
                case FROM_TYPE_VIEW_ORDER_LIST:{
                    int fromView = getIntent().getIntExtra(FROM_TYPE_ID,0);
                    LCLog.e("fromView = "+fromView);
                    Intent intent = new Intent(this, MainActivity.class);
                    intent.putExtra(FROM_TYPE_ID,fromView);
                    setResult(fromView, intent);
                    finish();
                    break;
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_text:
            case R.id.left_group:{
                finish();
                break;
            }

            case R.id.order_submit2:{
                //去支付


                if (addressInfoTv.getText().toString().isEmpty()||userNameTv.getText().toString().isEmpty()||phoneTv.getText().toString().isEmpty()){
                    LSCToast.show(this,"请添加收货地址！");
                    return;
                }else {
                        payOrder();
                }
                break;
            }

            case R.id.order_submit5:{
                //确认收货
                new AlertDialog.Builder(this)
                        .setTitle("确认收货？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (fromType!=FROM_TYPE_VIEW_CAR_LIST) {
                                    DataManager.getData(MODEL_PROCESS_3, NetHelper.Order.doneOrder(orderId), OrderInfoActivity.this);
                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();

                break;
            }
            case R.id.address_rl:
            case R.id.add_address:{
                //选择收货地址
                if (fromType==FROM_TYPE_VIEW_CAR_LIST) {
                    //生成订单时 选择收货地址
                    Intent intent = new Intent(this, AddressListActivity.class);
                    intent.putExtra(FROM_TYPE_ID, FROM_TYPE_VIEW_CREAT_ORDER);
                    startActivityForResult(intent, FROM_TYPE_VIEW_CREAT_ORDER);
                }
                break;
            }

        }
        super.onClick(v);
    }



    /**
     * 提交订单
     */
    private void payOrder(){

        creatOrderModel = new CreatOrderModel();
        creatOrderModel.user_id= UserConfig.getConfigUserId();
        creatOrderModel.address=addressInfoTv.getText().toString();
        creatOrderModel.truename= userNameTv.getText().toString();
        creatOrderModel.mobile= phoneTv.getText().toString();

            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            builder.addFormDataPart("action", "addorder");
            builder.addFormDataPart("userid", UserConfig.getConfigUserId());

            builder.addFormDataPart("person", userNameTv.getText().toString());
            builder.addFormDataPart("address", addressInfoTv.getText().toString());
            builder.addFormDataPart("tel", phoneTv.getText().toString());
            builder.addFormDataPart("shipid", cartID);
            Request request = new Request.Builder().url(NetHelper.Car.addOrder().getUrl()).post(builder.build()).build();
            HttpConnection.getHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {
                            LSCToast.show(OrderInfoActivity.this, "服务器请求失败!");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    final String string = response.body().string();
                    LCLog.e("string="+string);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {
                            if (!Tools.isGoodJson(string)){
                                LSCToast.show(OrderInfoActivity.this, "服务器请求失败!");
                            }else {
                                Gson gson = new GsonBuilder().serializeNulls().create();
                                AboutModel userInfo = gson.fromJson(string, AboutModel.class);
                                if (userInfo == null || userInfo.equals("")) {
                                    LSCToast.show(OrderInfoActivity.this, "服务器请求失败!");
                                }else if (userInfo.status==NET_ERROR||userInfo.status!=NET_SUSSEC){
                                    LSCToast.show(OrderInfoActivity.this, userInfo.mes);
                                } else {
                                    LSCToast.show(OrderInfoActivity.this, userInfo.mes);
                                    OrderInfoActivity.this.finish();
                                }
                            }
                        }
                    });
                }
            });

        }

    public void onResume() {
        super.onResume();
    }
    public void onPause() {
        super.onPause();
    }
}
